import { defineConfig, loadEnv } from 'vite'
import Components from 'unplugin-vue-components/vite'
import requireTransform from 'vite-plugin-require-transform' // 1. 引入插件
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path';
import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
import ViteFonts from 'unplugin-fonts/vite'
import { fileURLToPath, URL } from 'node:url'
import viteCompression from 'vite-plugin-compression'

export default defineConfig(({mode}) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_BASE_API,MINIO_CONSOLE_ADDRESS } = env;
  return {
    plugins: [
      vue({
        template: { transformAssetUrls }
      }),
      viteCompression({
        algorithm: 'gzip',
        ext: 'gz',
        deleteOriginFile: true,
        threshold: 512,
      }),
      Vuetify(),
      Components(),
      ViteFonts({
        google: {
          families: [{
            name: 'Roboto',
            styles: 'wght@100;300;400;500;700;900',
          }],
        },
      }),
      // 2. 添加以下代码
      requireTransform({
        fileRegex: /.js$|.vue$/,
      }),
    ],
    server: {
      proxy: {
        "/api": {
          // target: "http://43.136.84.55:8082",
          // target: "http://localhost:8082",
          target: VITE_BASE_API,
          changeOrigin: true,
          //rewrite: (path) => path.replace(/^\/api/, ""),
        },
        "/dictionary":{
          target: MINIO_CONSOLE_ADDRESS,
          changeOrigin: true,
        }
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
        //"@": resolve(__dirname, "./src")
      },
      extensions: [
        '.js',
        '.json',
        '.jsx',
        '.mjs',
        '.ts',
        '.tsx',
        '.vue',
      ],
    },
    build: {
      // 指定输出路径
      outDir: 'dist',
      //构建后是否生成 source map 文件
      sourcemap: false,
      // 多页面打包配置
      rollupOptions: {
        input: {
          // 配置所有页面路径，使得所有页面都会被打包
          main: resolve(__dirname, 'index.html'),
          login: resolve(__dirname, 'login.html'),
          admin: resolve(__dirname, 'admin.html'),
        },
        output:{
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        }
      }
    }
  }
})